package zy.dao.wx.authorizer.impl;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import zy.dao.BaseDaoImpl;
import zy.dao.wx.authorizer.AuthorizerDAO;
import zy.entity.wx.authorizer.T_Wx_Authorizer;

@Repository
public class AuthorizerDAOImpl extends BaseDaoImpl implements AuthorizerDAO{
	
	@Override
	public T_Wx_Authorizer load(String wa_appid) {
		StringBuffer sql = new StringBuffer("");
		sql.append(" SELECT wa_id,wa_appid,wa_access_token,wa_refresh_token,wa_expire_time");
		sql.append(" FROM t_wx_authorizer t");
		sql.append(" WHERE wa_appid = :wa_appid");
		sql.append(" LIMIT 1");
		try {
			return namedParameterJdbcTemplate.queryForObject(sql.toString(), new MapSqlParameterSource().addValue("wa_appid", wa_appid),
					new BeanPropertyRowMapper<>(T_Wx_Authorizer.class));
		} catch (Exception e) {
			return null;
		}
	}
	
	@Override
	public void save(T_Wx_Authorizer authorizer) {
		StringBuffer sql = new StringBuffer("");
		sql.append("INSERT INTO t_wx_authorizer");
		sql.append(" (wa_appid,wa_access_token,wa_refresh_token,wa_expire_time)");
		sql.append(" VALUES(:wa_appid,:wa_access_token,:wa_refresh_token,:wa_expire_time)");
		KeyHolder holder = new GeneratedKeyHolder(); 
		namedParameterJdbcTemplate.update(sql.toString(), new BeanPropertySqlParameterSource(authorizer),holder);
		authorizer.setWa_id(holder.getKey().intValue());
	}
	
	@Override
	public void update(T_Wx_Authorizer authorizer) {
		StringBuffer sql = new StringBuffer("");
		sql.append("UPDATE t_wx_authorizer");
		sql.append(" SET wa_access_token=:wa_access_token");
		sql.append(" ,wa_refresh_token=:wa_refresh_token");
		sql.append(" ,wa_expire_time=:wa_expire_time");
		sql.append(" WHERE wa_appid=:wa_appid");
		namedParameterJdbcTemplate.update(sql.toString(), new BeanPropertySqlParameterSource(authorizer));
	}
}
